﻿
Imports std
Imports tcpServer2
Imports runrroom

Public Class lrserver
    Inherits rrserver

    Public Sub New()
        MyBase.New(connection_const.port.localrun)
        insertMatchAction(AddressOf matchUpdateStatus)
        insertHandleAction(AddressOf updateStatus)
    End Sub

    Protected Overrides Function return_jobid() As Boolean
        Return False
    End Function

    Protected Overrides Function run(ByRef id As String, ByVal cmd As vector(Of String), _
                                     ByVal distrRuleId As String, ByVal distrRule As String, _
                                     ByRef errorInfo As String) As Boolean
        If cmd Is Nothing OrElse cmd.size() <> 1 Then
            errorInfo = "do not have valid command sent to lrserver."
            Return False
        End If
        If Not jobmgr().addjob(id, cmd(0)) Then
            errorInfo = "cannot add job to jobmgr, id " + id + ", cmd " + cmd(0)
            Return False
        Else
            Return True
        End If
    End Function

    Protected Overrides Function status(ByVal id As String, ByRef percentage As Int64, _
                                        ByRef errorInfo As String) As Boolean
        Dim p As percentage_t = Nothing
        If jobmgr().percent(id, p) Then
            percentage = (+p)
            Return True
        Else
            errorInfo = "cannot find job " + id
            Return False
        End If
    End Function

    Protected Shared Function matchUpdateStatus(ByVal p As pair(Of String, String)) As Boolean
        Return matchAction(p, protocols.actions.updateStatus)
    End Function

    Protected Shared Sub updateStatus(ByVal handle As talkHandle, ByVal p As vector(Of pair(Of String, String)))
        Dim jobid As String = Nothing
        Dim perc As SByte = 0
        Dim foundPerc As Boolean = False
        For i As Int64 = 0 To p.size() - 1
            If matchProtocol(p(i), protocols.jobid) Then
                copy(jobid, action(p(i)))
            ElseIf matchProtocol(p(i), protocols.percentage) Then
                Dim tmp As SByte = 0
                If convertor.tosbyte(result(p(i)), tmp) Then
                    foundPerc = True
                    perc = tmp
                End If
            End If
        Next

        If Not isemptystring(jobid) AndAlso foundPerc AndAlso _
           jobmgr().updatePercent(jobid, New percentage_t(perc)) Then
            return_success(handle)
        Else
            Dim msg As String = Nothing
            msg = "failed to update percent to job " + jobid
            raiseError(msg, errorHandle.errorType.warning)
            return_failed(handle, msg)
        End If
    End Sub
End Class
